import java.io.*;
import java.util.*;

public class Journal implements Serializable {
    private String filePath;
    HashMap<Date, Query> records;

    public Journal(String path) {
        filePath = path;
        records = new HashMap<Date, Query>();
    }

    public HashMap<Date, Query> getRecords(){
        return records;
    }

    public Journal getLastChanges(Date date) {
        Journal result = new Journal("");
        result.records = new HashMap<Date, Query>();
        for(Map.Entry<Date, Query> query : this.getRecords().entrySet()) {
                if(query.getKey().after(date))
                    result.records.put(query.getKey(), query.getValue());
        }
        return result;
    }

    public void flushToFile(){
        ObjectOutputStream out = null;
        try {
            out = new ObjectOutputStream(new FileOutputStream(filePath));
            Message temp = new Message(records);
            out.writeObject(temp);
            out.flush();
            out.close();
        } catch (IOException e) {
            System.out.println("Error! " + e.getMessage());
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    System.out.println("Error of closing file!");
                }
            }
        }
    }

    public void add(Query query) {
        records.put(Calendar.getInstance().getTime(), query);
    }
}
